import { NestFactory } from '@nestjs/core';
import { Logger } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

import { AppModule } from './app.module';
import { CustomerLogger } from '../infra/service/logger.service';
import { env } from '../settings';

function addSwaggerDocument(app: NestExpressApplication) {
  const config = new DocumentBuilder()
    .setTitle(env.SWAGGER_TITLE)
    .setDescription(env.SWAGGER_DESCRIPTION)
    .setVersion(env.VERSION)
    .addBearerAuth()
    .build();

  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup(env.SWAGGER_DOCS, app, documentFactory);
}

async function bootstrap() {
  const app = (await NestFactory.create(AppModule, {
    logger: new CustomerLogger(),
  })) as NestExpressApplication;

  addSwaggerDocument(app);

  // 允许跨域
  app.enableCors();
  app.setGlobalPrefix('api');

  // 静态文件目录
  app.useStaticAssets(env.UPLOAD_DIR, { prefix: '/uploads/' });

  await app.listen(env.PORT);

  const logger = new Logger('bootstrap');
  logger.log(`Application listening on port ${env.PORT}`);
}
bootstrap();
